package com.basic.business.common.utils;

import com.basic.business.common.constants.Constants;
import com.basic.business.common.redis.RedisCacheUtils;
import com.basic.business.order.domain.TOrdersMerge;
import com.basic.common.core.domain.entity.SysUserInfo;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 用户工具类
 */
public class UserUtils {

    /**
     * 获取用户缓存信息
     */
    public static List<SysUserInfo> getUserCache(){
        return RedisCacheUtils.getCacheObject(Constants.USER_REDIS_KEY);
    }

    /**
     * 根据用户编号获取用户id
     */
    private static Object getUserIdByUserCode(String userCode){
        List<SysUserInfo> datas = getUserCache();
        if (StringUtils.isNull(datas))
        {
           return StringUtils.EMPTY;
        }

        for (SysUserInfo data : datas) {
            if (StringUtils.equals(data.getUserCode(), userCode)) {
                return data.getUserId();
            }
        }
        return userCode;
    }


    /**
     * 提取整理人，并将userCode转换为userId
     */
    public static String extractUserId(List<TOrdersMerge> merges) {
        if (StringUtils.isNull(merges)) {
            return StringUtils.EMPTY;
        }

        return merges.stream()
                .map(TOrdersMerge::getSellerMemo)
                .filter(StringUtils::isNotNull)
                .map(memo -> {
                    Pattern pattern = Pattern.compile("【整理人：(\\d{6})】");
                    Matcher matcher = pattern.matcher(memo);
                    List<String> userIds = new ArrayList<>();

                    while (matcher.find()) {
                        String userCode = matcher.group(1);
                        Object userId = getUserIdByUserCode(userCode);
                        if (userId != null) {
                            userIds.add(userId.toString());
                        }
                    }

                    return userIds;
                })
                .flatMap(List::stream)
                .distinct()
                .collect(Collectors.joining(","));
    }

}
